<script setup lang='ts'>
import Footer from '@/pages/footer/footer.vue'
import { useGetHomeSearchResult } from '@fl/api/man-api'
import { CreateUUID } from '@fl/components/uuid'
import { ElPagination } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { computed, ref } from 'vue'
import { useRoute } from 'vue-router'

import Conditions from './component/conditions.vue'
import Crumbs from './component/crumbs.vue'
import ListItem from './component/list.vue'
import SortItem from './component/sort-item.vue'

const route = useRoute()
const conditRef = ref()

const list = ref<any>({})
const conditionMap = ref<any>({})

const sortMap = [
    {
        label: '综合排序',
        value: 1,
    },
    {
        label: '新品',
        value: 1,
    },
    {
        label: '销量',
        sort: true,
        value: 1,
    },
    {
        label: '价格',
        sort: true,
        value: 1,
    },
]
// 缓存已选中条件
const selected = ref<any>([])

const initState = {
    attr: '', // 属性
    bids: '',
    keyword: '',
    leaf: '1', // 是否叶子类目 1 是 0 否
    page: 1,
    path: '', // 品类路径
    size: 10,
    sort: '',
    type: 1, // 类型 1 商品 2 供应商
}

const state = ref(cloneDeep(initState))

const pages = ref<any>({
    page: 1,
    size: 10,
})

const crumbs = ref<any>([
    {
        label: '全部结果',
        value: '',
    },
])

function getParams(val?: any) {
    const target: any = crumbs.value.filter((v: any) => v.value)
    const brands: any = []
    const other: any = []
    let path = ''
    target.forEach((v: any) => {
        // 品牌ID列表
        if (v?.isBrand) {
            brands.push(v.isBrand)
        }
        else if (v?.path) { // 类目
            path = v.path
        }
        else { // 动态属性
            other.push(v)
        }
    })

    // 动态属性查询条件拼接
    const attr = other.map((v: any) => {
        return v.label.replace(':', '=')
    })

    const params: any = {
        ...state.value,
        ...route.query,
        attr: attr.join(';'),
        bids: brands.join(','),
        page: pages.value.page,
        size: pages.value.size,
        ...val,
    }
    if (path) {
        params.path = path
        params.leaf = 1 // 叶子节点
    }
    return params
}

const { isPending, mutateAsync } = useGetHomeSearchResult()
function getData(val?: any) {
    mutateAsync(getParams(val), {
        onError(error: any) {
            console.error(error)
        },
        onSuccess: (res: any) => {
            const { productList, searchCondition } = res
            list.value = productList ?? {}
            conditionMap.value = searchCondition ?? {}
        },
    })
}

// 用于首页优选品牌进入传入id
function init() {
    if (route.query?.bids) {
        const value = route.query.bids
        crumbs.value.push({
            isBrand: value,
            label: `品牌:${route.query.name}`,
            value,
        })
    }

    getData()
}
init()

// 品牌属性规格 转化成查询条件
function getcondits(data: any) {
    const { attr, brand, category } = data
    const target: any = []
    // 添加品牌属性
    if (brand?.length) {
        const children = brand.map((v: any) => {
            return {
                img: v.brandLogo,
                label: v.brandName,
                value: v.brandId,
            }
        })
        if (children.length > 1) {
            target.push({
                children,
                expand: false,
                id: CreateUUID(),
                label: '品牌',
                valueType: 'image', // 品牌
            })
        }
    }
    // 添加动态属性
    if (attr && JSON.stringify(attr) !== '{}') {
        Object.keys(attr).forEach((key: string) => {
            const children = attr[key].map((label: any) => {
                return {
                    label,
                    value: CreateUUID(),
                }
            })
            // 存在多个可选属性值 才展示
            if (children.length > 1) {
                target.push({
                    children,
                    expand: false,
                    id: CreateUUID(),
                    label: key,
                    valueType: 'text',
                })
            }
        })
    }
    // 添加类目
    if (category && JSON.stringify(category) !== '{}') {
        Object.keys(category).forEach((key: string) => {
            const children = category[key].map((item: any) => {
                return {
                    label: item.split('|')[1],
                    path: item.split('|')[0],
                    value: CreateUUID(),
                }
            })
            if (children.length > 1) {
                target.push({
                    children,
                    expand: false,
                    id: CreateUUID(),
                    label: key.split('|')[1],
                    path: key.split('|')[0],
                    valueType: 'text',
                })
            }
        })
    }
    return target
}

const opts = computed(() => {
    return getcondits(conditionMap.value)
})

function clickCondit(val: any, { item }) {
    // 缓存数据
    const target = selected.value.some((v: any) => v.id === val.id)
    if (!target) {
        selected.value.push(val)
    }

    const flag = crumbs.value.some((v: any) => v.value === val.id)
    if (!flag) {
        const active: any = {
            isBrand: item.img ? item.value : '', // 品牌查询条件 缓存id
            label: `${val.label}:${item.label}`,
            value: val.id,
        }
        // 紧类目存在path
        if (item?.path) {
            active.path = item.path
        }
        // 拼接已选查询条件
        crumbs.value.push(active)
    }

    getData()
}

function clickSort(val: any) {
    console.log(4444, val)
}
function sortChange(val: any) {
    console.log(333, val)
}

// 去掉已选查询条件
function close(item: any) {
    const target = cloneDeep(crumbs.value)
    const slectedMap = cloneDeep(selected.value)
    crumbs.value = target.filter((v: any) => v.value !== item.value)

    // 删除对应已选中条件 恢复可选
    selected.value = slectedMap.filter((v: any) => v.id !== item.value)

    // 恢复可选条件
    conditRef.value.showItem({ id: item.value })

    getData()
}
</script>

<template>
    <div class="mx-auto mt-20 w-1300">
        <Crumbs class="mb-20 mt-20"
                :data="crumbs"
                @close="close"
        />

        <div class="p-30 bg-#fff rounded-4 w-full">
            <Conditions ref="conditRef"
                        :data="opts"
                        @click-condit="clickCondit"
            />

            <!-- TODO:暂时隐藏 -->
            <SortItem :data="sortMap"
                      class="py-30 !hidden"
                      @click-handle="clickSort"
                      @sort-change="sortChange"
            />

            <el-skeleton v-if="isPending"
                         :rows="5"
            />

            <ListItem v-else
                      :data="list"
            />

            <ElPagination v-model:current-page="pages.page"
                          v-model:page-size="pages.size"
                          layout="total, sizes, prev, pager, next, jumper"
                          :total="list?.total ?? 0"
                          small
                          background
                          class="mt-20 flex justify-end"
                          @size-change="() => getData()"
                          @current-change="() => getData()"
            />
        </div>
    </div>

    <Footer />
</template>

<style lang="less" scoped>

</style>
